package com.bjpowernode.controller;

import com.bjpowernode.beans.User;
import com.bjpowernode.dto.ResultDTO;
import com.bjpowernode.exception.MyException;
import com.bjpowernode.services.UserServices;
import com.bjpowernode.tools.MyTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserServices userServices;


    //登录[需要考虑是否记录登录信息的cookies]
    @RequestMapping("login.action")
    public ResultDTO login(String id, String password, String rememberMe, HttpServletResponse response, HttpSession httpSession) throws MyException {

        System.out.println("rememberMe:" + rememberMe);
        User loginUser = userServices.login(id, password);
        ResultDTO resultDTO = new ResultDTO();
        if (loginUser == null) {
            throw new MyException("用户账号或者密码错误，登录失败");
        }


        //如果需要添加cookies，则需要添加用户账号id和用户密码的cookies
        if (rememberMe != null && rememberMe.equals("true")) {
            //记录cookie，且10天
            //创建cookie
            //cookie是KV，但是规则是K和V都是String
            Cookie cookieId = new Cookie("id", id);
            //设置作用域Path,也就是哪个当前IP地址哪个网址有效()
            //如果设置/，则对当前IP地址的所有网址有效
            cookieId.setPath("/");
            //设置生命
            //不设置浏览器关闭就死
            cookieId.setMaxAge(10 * 24 * 60 * 60);

            Cookie cookiePwd = new Cookie("password", password);
            cookiePwd.setPath("/");
            cookiePwd.setMaxAge(10 * 24 * 60 * 60);

            //使用响应对象指派浏览器添加cookie
            response.addCookie(cookieId);
            response.addCookie(cookiePwd);

        }

        resultDTO.setMess("登录成功");
        resultDTO.setData(loginUser);
        //立即加载到HttpSession里面
        httpSession.setAttribute("user", loginUser);
        return resultDTO;
    }

    //登出[需要删除登录信息的cookies]
    @RequestMapping("logout.action")
    public ResultDTO logout(HttpSession httpSession, HttpServletRequest request, HttpServletResponse response) throws MyException {


        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setMess("登出成功");
        httpSession.removeAttribute("user");

        //如果有cookie，需要清除掉cookie
        //这里的cookie仅仅是请求对象携带的KV,也仅仅只有KV数据
        //因此在修改的时候需要，响应给浏览器
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("id") || cookie.getName().equals("password")) {
                cookie.setPath("/");
                cookie.setMaxAge(0);
                //必须响应给浏览器
                response.addCookie(cookie);
            }
        }


        //顶替办法，也可以删除
//        Cookie cookieId = new Cookie("id","");
//        cookieId.setPath("/");
//        cookieId.setMaxAge(0);
//        Cookie cookiePwd= new Cookie("password", "");
//        cookiePwd.setPath("/");
//        cookiePwd.setMaxAge(0);
//        response.addCookie(cookieId);
//        response.addCookie(cookiePwd);


        return resultDTO;
    }

    //获取当前用户【这里有BUG】
    @RequestMapping("get.action")
    public ResultDTO get(HttpServletRequest request, HttpSession httpSession) throws Exception {
        ResultDTO resultDTO = new ResultDTO();
        Object user = httpSession.getAttribute("user");


        //第一次判断，并尝试自动登录
        if (user == null) {
            System.out.println("第一判断，并尝试自动登录");
            MyTools.loginCookies(request, userServices, () -> {
                throw new MyException("需要登录用户才能使用该功能，请登录");
            });
        }

        //第二次判断
        //再次获取HttpSession
        System.out.println("第二次判断，再次获取httpSession，仍然没用用户则直接失败.............");
        user = httpSession.getAttribute("user");
        if (user == null) {
            System.out.println("第二次判断，失败.............");
            resultDTO.setMess("没有登录用户");
            resultDTO.setData(null);
        } else {
            System.out.println("第二次判断，成功.............");
            resultDTO.setMess("可以获取登录用户");
            resultDTO.setData(((User) user).getName());
        }

        return resultDTO;
    }

}
